package com.zhiliao.destruction;

import java.io.*;
import java.lang.reflect.Constructor;

/**
 * 单例全：https://baijiahao.baidu.com/s?id=1768825310691501372&wfr=spider&for=pc
 */
public class SingTonDestoryTest {

    private static final String FILE_PATH = "hello.txt";

    public static void main(String[] args) throws Exception {

//        testWriteFile();
//        System.out.println(readObjectFile());
//        System.out.println(readObjectFile());
//        System.out.println(readObjectFile());

       /* Class<SingleTon> c = SingleTon.class;
        Constructor<?> constructor = c.getDeclaredConstructor();
        constructor.setAccessible(true);
        System.out.println(constructor.newInstance());
        System.out.println(constructor.newInstance());
        System.out.println(constructor.newInstance());*/

        System.out.println(SingletonInstance.INSTANCE);
        System.out.println(SingletonInstance.INSTANCE);
        Class<SingletonInstance> instanceClass = SingletonInstance.class;
        Constructor<SingletonInstance> constructor = instanceClass.getDeclaredConstructor(String.class);
        constructor.setAccessible(true);
        System.out.println(instanceClass.newInstance());
        SingletonInstance.valueOf("");
    }

    public static void testWriteFile() {

        ObjectOutputStream objectOutputStream = null;
        try {
            objectOutputStream = new ObjectOutputStream(new FileOutputStream(FILE_PATH));
            SingleTon singleTon = SingleTon.getInstance();
            objectOutputStream.writeObject(singleTon);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (objectOutputStream != null) {
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static Object readObjectFile() {
        ObjectInputStream objectInputStream = null;
        try {
            objectInputStream = new ObjectInputStream(new FileInputStream(FILE_PATH));

            return objectInputStream.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (objectInputStream != null) {
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }



}
